<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络云工作台历史告警分析报表系统</title>
    <!-- 引入Chart.js库 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        h1 {
            text-align: center;
            font-size: 2em;
            margin-bottom: 10px;
        }

        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: #007bff;
            color: white;
        }

        .btn-success {
            background-color: #28a745;
            color: white;
        }

        .btn-info {
            background-color: #17a2b8;
            color: white;
        }

        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }

        .btn-danger {
            background-color: #dc3545;
            color: white;
        }

        button:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }

        .query-form {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 15px;
        }

        .form-group {
            flex: 1;
            min-width: 200px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .alarm-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        th {
            background-color: #f8f9fa;
            font-weight: bold;
            position: sticky;
            top: 0;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .status-processing {
            color: #ffc107;
            font-weight: bold;
        }

        .status-resolved {
            color: #28a745;
            font-weight: bold;
        }

        .status-unresolved {
            color: #dc3545;
            font-weight: bold;
        }

        .level-critical {
            color: #dc3545;
            font-weight: bold;
        }

        .level-major {
            color: #fd7e14;
            font-weight: bold;
        }

        .level-minor {
            color: #ffc107;
            font-weight: bold;
        }

        .level-warning {
            color: #28a745;
            font-weight: bold;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .page-info {
            font-size: 14px;
            color: #666;
        }

        .import-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .file-input {
            margin-bottom: 15px;
        }

        .file-input input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            color: white;
            font-weight: bold;
            z-index: 1000;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transform: translateX(200%);
            transition: transform 0.3s ease;
        }

        .notification.show {
            transform: translateX(0);
        }

        .notification.success {
            background-color: #28a745;
        }

        .notification.error {
            background-color: #dc3545;
        }

        .notification.info {
            background-color: #17a2b8;
        }

        /* LLM分析进度条样式 */
        .llm-progress-container {
            display: none;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .llm-progress-container.show {
            display: block;
        }

        .llm-progress-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .llm-progress-title {
            font-size: 16px;
            font-weight: bold;
            color: #667eea;
        }

        .llm-progress-status {
            font-size: 14px;
            color: #666;
        }

        .llm-progress-bar-wrapper {
            width: 100%;
            height: 30px;
            background-color: #e9ecef;
            border-radius: 15px;
            overflow: hidden;
            position: relative;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }

        .llm-progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 14px;
            position: relative;
            overflow: hidden;
        }

        .llm-progress-bar::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            animation: shimmer 2s infinite;
        }

        @keyframes shimmer {
            0% { left: -100%; }
            100% { left: 100%; }
        }

        .llm-progress-steps {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e9ecef;
        }

        .llm-progress-step {
            display: flex;
            align-items: center;
            padding: 8px 0;
            font-size: 14px;
            color: #666;
        }

        .llm-progress-step.active {
            color: #667eea;
            font-weight: bold;
        }

        .llm-progress-step.completed {
            color: #28a745;
        }

        .llm-progress-step-icon {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        .llm-progress-step .llm-progress-step-icon {
            background-color: #e9ecef;
            color: #999;
        }

        .llm-progress-step.active .llm-progress-step-icon {
            background-color: #667eea;
            color: white;
        }

        .llm-progress-step.completed .llm-progress-step-icon {
            background-color: #28a745;
            color: white;
        }

        /* 告警详情模态框样式 */
        .detail-modal {
            display: none;
            position: fixed;
            z-index: 3000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease;
        }

        .detail-modal.show {
            display: block;
        }

        .detail-modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 80%;
            max-width: 800px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.2);
            animation: slideDown 0.3s ease;
        }

        .detail-modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .detail-modal-header h2 {
            margin: 0;
            font-size: 1.5em;
        }

        .detail-modal-body {
            padding: 30px;
            max-height: 70vh;
            overflow-y: auto;
        }

        .detail-item {
            display: flex;
            padding: 12px 0;
            border-bottom: 1px solid #eee;
        }

        .detail-item:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: bold;
            color: #667eea;
            width: 180px;
            flex-shrink: 0;
        }

        .detail-value {
            flex: 1;
            color: #333;
            word-break: break-all;
        }

        .btn-detail {
            background-color: #667eea;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .btn-detail:hover {
            background-color: #5568d3;
            transform: translateY(-1px);
        }

        /* 柱状图区域样式 */
        .charts-section {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .charts-section h2 {
            color: #667eea;
            margin-bottom: 25px;
            font-size: 1.8em;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 30px;
        }

        .chart-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .chart-container h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.2em;
            text-align: center;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .chart-wrapper {
            position: relative;
            height: 350px;
        }

        .charts-loading {
            text-align: center;
            padding: 50px;
            color: #999;
            font-size: 1.2em;
        }

        @media (max-width: 1024px) {
            .charts-grid {
                grid-template-columns: 1fr;
            }
        }

        /* 数据分析模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease;
        }

        .modal.show {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background-color: #fefefe;
            margin: 3% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 1100px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.2);
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 1.8em;
        }

        .close {
            color: white;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            line-height: 1;
        }

        .close:hover,
        .close:focus {
            transform: scale(1.2);
        }

        .modal-body {
            padding: 30px;
            max-height: 70vh;
            overflow-y: auto;
        }

        .analysis-section {
            margin-bottom: 35px;
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            border-left: 5px solid #667eea;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .analysis-section:last-child {
            margin-bottom: 0;
        }

        .analysis-section h3 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.5em;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .analysis-section h3::before {
            content: "📊";
            font-size: 1.2em;
        }

        .analysis-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
        }

        .stat-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(102,126,234,0.3);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card h4 {
            margin: 0 0 10px 0;
            font-size: 1.1em;
            opacity: 0.9;
        }

        .stat-card .value {
            font-size: 2.5em;
            font-weight: bold;
            margin: 10px 0;
        }

        .stat-card .label {
            font-size: 0.9em;
            opacity: 0.8;
        }

        .top-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .top-list li {
            background: #f8f9fa;
            margin-bottom: 12px;
            padding: 15px 20px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }

        .top-list li:hover {
            background: #e9ecef;
            border-left-color: #667eea;
            transform: translateX(5px);
        }

        .top-list .rank {
            background: #667eea;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .top-list .item-content {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 15px;
        }

        .top-list .item-name {
            flex: 1;
            font-weight: 500;
            color: #333;
        }

        .top-list .item-count {
            background: #667eea;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
            min-width: 60px;
            text-align: center;
        }

        .level-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .level-item {
            background: white;
            padding: 15px;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .level-item:hover {
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102,126,234,0.2);
        }

        .level-item .level-name {
            font-weight: bold;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .level-item .level-count {
            font-size: 1.8em;
            font-weight: bold;
            color: #667eea;
        }

        .level-item .level-percent {
            color: #6c757d;
            font-size: 0.9em;
            margin-top: 5px;
        }

        .summary-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
        }

        .summary-box h4 {
            margin: 0 0 15px 0;
            font-size: 1.2em;
        }

        .summary-box p {
            margin: 8px 0;
            line-height: 1.6;
        }

        /* 文件监听提示模态框样式 */
        .file-alert-modal {
            display: none;
            position: fixed;
            z-index: 4000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease;
        }

        .file-alert-modal.show {
            display: block;
        }

        .file-alert-modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 0;
            border-radius: 12px;
            width: 80%;
            max-width: 500px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.2);
            animation: slideDown 0.3s ease;
        }

        .file-alert-modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .file-alert-modal-header h2 {
            margin: 0;
            font-size: 1.5em;
        }

        .file-alert-modal-body {
            padding: 30px;
        }

        .file-alert-modal-body p {
            margin: 0 0 20px 0;
            font-size: 1.1em;
            color: #333;
            line-height: 1.6;
        }

        .file-alert-modal-body .filename {
            font-weight: bold;
            color: #667eea;
            word-break: break-all;
        }

        .file-alert-modal-footer {
            padding: 20px 30px;
            background-color: #f8f9fa;
            border-radius: 0 0 12px 12px;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }

        .btn-ignore {
            background-color: #6c757d;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .btn-ignore:hover {
            background-color: #5a6268;
            transform: translateY(-2px);
        }

        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .btn-group {
                justify-content: center;
            }

            .form-row {
                flex-direction: column;
            }

            .form-group {
                min-width: 100%;
            }

            .modal-content {
                width: 95%;
                margin: 5% auto;
            }

            .stat-grid,
            .level-stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>网络云工作台历史告警分析报表系统</h1>
        </header>

        <div class="controls">
            <div class="btn-group">
                <button class="btn-primary" id="refreshBtn">刷新记录</button>
                <button class="btn-info" id="monitorBtn">监听excel文件</button>
                <button class="btn-danger" id="stopMonitorBtn" style="display: none;">停止监听</button>
                <button class="btn-success" id="llmAnalyzeBtn">调用本地大模型分析告警并生成Markdown文档</button>
                <button class="btn-warning" id="sendEmailBtn">发送邮件</button>
            </div>
        </div>

        <!-- LLM分析进度条 -->
        <div class="llm-progress-container" id="llmProgressContainer">
            <div class="llm-progress-header">
                <div class="llm-progress-title">🤖 正在调用本地大模型分析...</div>
                <div class="llm-progress-status" id="llmProgressStatus">准备中...</div>
            </div>
            <div class="llm-progress-bar-wrapper">
                <div class="llm-progress-bar" id="llmProgressBar" style="width: 0%">
                    <span id="llmProgressPercent">0%</span>
                </div>
            </div>
            <div class="llm-progress-steps">
                <div class="llm-progress-step" id="step1">
                    <div class="llm-progress-step-icon">1</div>
                    <span>读取Excel文件数据</span>
                </div>
                <div class="llm-progress-step" id="step2">
                    <div class="llm-progress-step-icon">2</div>
                    <span>分析数据并生成统计结果</span>
                </div>
                <div class="llm-progress-step" id="step3">
                    <div class="llm-progress-step-icon">3</div>
                    <span>生成数据可视化图表</span>
                </div>
                <div class="llm-progress-step" id="step4">
                    <div class="llm-progress-step-icon">4</div>
                    <span>调用Qwen3:14b大模型进行智能分析</span>
                </div>
                <div class="llm-progress-step" id="step5">
                    <div class="llm-progress-step-icon">5</div>
                    <span>生成Markdown分析报告</span>
                </div>
            </div>
        </div>

        <div class="import-section">
            <h3>导入告警数据</h3>
            <div class="file-input">
                <input type="file" id="alarmFile" accept=".xlsx,.xls">
                <p style="margin-top: 10px; color: #666; font-size: 14px;">仅支持Excel文件（.xlsx, .xls）</p>
            </div>
            <button class="btn-success" id="importBtn">导入</button>
        </div>

        <!-- 柱状图展示区域 -->
        <div class="charts-section" id="chartsSection">
            <h2>📈 告警数据柱状图分析</h2>
            <div class="charts-grid">
                <!-- 场景1：告警标题趋势图 -->
                <div class="chart-container">
                    <h3>📊 场景一：告警标题趋势图（TOP20）</h3>
                    <div class="chart-wrapper">
                        <canvas id="chart1"></canvas>
                    </div>
                </div>

                <!-- 场景2：设备告警趋势图 -->
                <div class="chart-container">
                    <h3>💻 场景二：设备告警趋势图（TOP20）</h3>
                    <div class="chart-wrapper">
                        <canvas id="chart2"></canvas>
                    </div>
                </div>

                <!-- 场景3：设备厂商趋势图 -->
                <div class="chart-container">
                    <h3>🏭 场景三：设备厂商（虚层）趋势图（TOP20）</h3>
                    <div class="chart-wrapper">
                        <canvas id="chart3"></canvas>
                    </div>
                </div>

                <!-- 场景4：告警级别趋势图 -->
                <div class="chart-container">
                    <h3>⚠️ 场景四：告警级别趋势图</h3>
                    <div class="chart-wrapper">
                        <canvas id="chart4"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="alarm-table">
            <table>
                <thead>
                    <tr>
                        <th>告警全局标识</th>
                        <th>告警标题</th>
                        <th>标准告警级别</th>
                        <th>告警类型</th>
                        <th>告警状态</th>
                        <th>告警发生时间</th>
                        <th>告警清除时间</th>
                        <th>大区</th>
                        <th>机房</th>
                        <th>设备名称</th>
                        <th>设备类型</th>
                        <th>设备厂商</th>
                        <th>派单状态</th>
                        <th>资源池</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="alarmTableBody">
                    <!-- 表格数据已清空 -->
                </tbody>
            </table>
        </div>

        <div class="pagination">
            <button class="btn-primary" id="prevPage">上一页</button>
            <span class="page-info">第 <span id="currentPage">1</span> 页，共 <span id="totalPages">1</span> 页</span>
            <button class="btn-primary" id="nextPage">下一页</button>
        </div>
    </div>

    <div class="notification" id="notification"></div>

    <!-- 文件监听提示模态框 -->
    <div id="fileAlertModal" class="file-alert-modal">
        <div class="file-alert-modal-content">
            <div class="file-alert-modal-header">
                <h2>📡 发现新文件</h2>
            </div>
            <div class="file-alert-modal-body">
                <p>检测到新的告警导出Excel文件：</p>
                <p class="filename" id="newFileName"></p>
            </div>
            <div class="file-alert-modal-footer">
                <button class="btn-ignore" onclick="closeFileAlert()">忽略</button>
            </div>
        </div>
    </div>

    <!-- 告警详情模态框 -->
    <div id="detailModal" class="detail-modal">
        <div class="detail-modal-content">
            <div class="detail-modal-header">
                <h2>📝 告警详情信息</h2>
                <span class="close" onclick="closeDetailModal()">&times;</span>
            </div>
            <div class="detail-modal-body" id="detailContent">
                <!-- 动态填充 -->
            </div>
        </div>
    </div>



    <script>
        // ==================== API配置 ====================
        // 后端API基础URL，请根据实际部署情况修改
        const BACKEND_URL = 'http://localhost:8000';  // 后端服务地址
        const API_BASE = `${BACKEND_URL}/api/v1/alarms`;
        // ==================================================
        
        // 当前页码和每页显示数量
        let currentPage = 1;
        const pageSize = 6;
        let totalAlarms = 0;
        
        // DOM元素,
        // DOM 元素（DOM Element）是指 文档对象模型（Document Object Model） 中的基本组成单元，代表 HTML 或 XML 文档中的一个标签（如 <div>、<p>、<button> 等）及其包含的内容、属性和相关行为。
        const alarmTableBody = document.getElementById('alarmTableBody');
        const currentPageEl = document.getElementById('currentPage');
        const totalPagesEl = document.getElementById('totalPages');
        const notificationEl = document.getElementById('notification');
        
        // 按钮事件监听
        document.getElementById('refreshBtn').addEventListener('click', refreshAlarms);
        document.getElementById('monitorBtn').addEventListener('click', startFileMonitoring);
        document.getElementById('stopMonitorBtn').addEventListener('click', stopFileMonitoring);
        document.getElementById('sendEmailBtn').addEventListener('click', sendEmail);
        document.getElementById('llmAnalyzeBtn').addEventListener('click', callLLMAnalyze);
        document.getElementById('importBtn').addEventListener('click', importAlarms);
        document.getElementById('prevPage').addEventListener('click', prevPage);
        document.getElementById('nextPage').addEventListener('click', nextPage);
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async function() {
            // 自动加载告警数据
            await refreshAlarms();
            // 加载柱状图数据
            await loadCharts();
            // 查询文件监听状态并同步按钮显示
            await checkMonitoringStatus();
            // 启动新文件检查轮询
            startNewFilePolling();
        });
        
        // 刷新告警记录
        async function refreshAlarms() {
            try {
                showNotification('正在刷新告警记录...', 'info');
                const response = await fetch(`${API_BASE}?skip=${(currentPage - 1) * pageSize}&limit=${pageSize}`);
                //对应到 backend/routes/alarms.py 的@router.get("/", response_model=List[Alarm])
                if (response.ok) {
                    const alarms = await response.json();
                    renderAlarms(alarms);
                    updatePagination();
                    showNotification('告警记录刷新成功', 'success');
                } else {
                    throw new Error('获取告警记录失败');
                }
            } catch (error) {
                console.error('刷新告警记录失败:', error);
                showNotification('刷新告警记录失败: ' + error.message, 'error');
            }
        }
        
        // 启动文件监听
        async function startFileMonitoring() {
            try {
                showNotification('正在启动文件监听服务...', 'info');
                const response = await fetch(`${API_BASE}/monitor/start`, {
                    method: 'POST'
                });
                if (response.ok) {
                    const result = await response.json();
                    showNotification(result.message || '文件监听服务启动成功', 'success');
                    // 切换按钮显示状态
                    document.getElementById('monitorBtn').style.display = 'none';
                    document.getElementById('stopMonitorBtn').style.display = 'inline-block';
                } else {
                    throw new Error('启动文件监听失败');
                }
            } catch (error) {
                console.error('启动文件监听失败:', error);
                showNotification('启动文件监听失败: ' + error.message, 'error');
            }
        }

        // 停止文件监听
        async function stopFileMonitoring() {
            try {
                showNotification('正在停止文件监听服务...', 'info');
                const response = await fetch(`${API_BASE}/monitor/stop`, {
                    method: 'POST'
                });
                if (response.ok) {
                    const result = await response.json();
                    showNotification(result.message || '文件监听服务已停止', 'success');
                    // 切换按钮显示状态
                    document.getElementById('monitorBtn').style.display = 'inline-block';
                    document.getElementById('stopMonitorBtn').style.display = 'none';
                } else {
                    throw new Error('停止文件监听失败');
                }
            } catch (error) {
                console.error('停止文件监听失败:', error);
                showNotification('停止文件监听失败: ' + error.message, 'error');
            }
        }

        // 查询文件监听状态
        async function checkMonitoringStatus() {
            try {
                const response = await fetch(`${API_BASE}/monitor/status`);
                if (response.ok) {
                    const result = await response.json();
                    // 根据后端返回的状态同步按钮显示
                    if (result.monitoring) {
                        // 正在监听中，显示停止按钮
                        document.getElementById('monitorBtn').style.display = 'none';
                        document.getElementById('stopMonitorBtn').style.display = 'inline-block';
                    } else {
                        // 未启动监听，显示启动按钮
                        document.getElementById('monitorBtn').style.display = 'inline-block';
                        document.getElementById('stopMonitorBtn').style.display = 'none';
                    }
                    console.log('文件监听状态:', result.message);
                }
            } catch (error) {
                console.error('查询文件监听状态失败:', error);
                // 查询失败时默认显示启动按钮
                document.getElementById('monitorBtn').style.display = 'inline-block';
                document.getElementById('stopMonitorBtn').style.display = 'none';
            }
        }

        // 启动新文件检查轮询
        function startNewFilePolling() {
            // 每3秒检查一次是否有新的告警导出文件
            setInterval(async () => {
                await checkNewFile();
            }, 3000);
        }

        // 检查是否有新文件
        async function checkNewFile() {
            try {
                const response = await fetch(`${API_BASE}/monitor/latest-file`);
                if (response.ok) {
                    const result = await response.json();
                    if (result.has_new_file && result.file) {
                        // 发现新文件，显示人工关闭的弹窗
                        const file = result.file;
                        const fileName = file.file_name;
                        showFileAlert(fileName, file.file_path);
                        console.log('发现新文件:', file);
                    }
                }
            } catch (error) {
                // 静默失败，不影响用户体验
                console.debug('检查新文件失败:', error);
            }
        }
        
        // 显示文件监听提示弹窗
        function showFileAlert(fileName, filePath) {
            document.getElementById('newFileName').textContent = fileName;
            document.getElementById('fileAlertModal').classList.add('show');
            
            // 保存文件路径以便后续操作使用
            window.currentFilePath = filePath;
        }
        
        // 关闭文件监听提示弹窗
        function closeFileAlert() {
            const modal = document.getElementById('fileAlertModal');
            modal.classList.remove('show');
        }

        // 发送邮件
        async function sendEmail() {
            try {
                showNotification('正在发送分析报告邮件...', 'info');
                const response = await fetch(`${API_BASE}/email/send`, {
                    method: 'POST'
                });
                if (response.ok) {
                    const result = await response.json();
                    showNotification(result.message || '邮件发送成功', 'success');
                } else {
                    throw new Error('发送邮件失败');
                }
            } catch (error) {
                console.error('发送邮件失败:', error);
                showNotification('发送邮件失败: ' + error.message, 'error');
            }
        }

        // 调用本地大模型分析告警并生成Markdown文档
        //document.getElementById 方法获取 HTML 文档中具有特定 ID 的元素，并将这些元素分别存储到对应的变量中
        async function callLLMAnalyze() {
            // 创建隐藏的文件输入元素
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.xlsx,.xls';
            fileInput.style.display = 'none';
            
            // 添加文件选择事件监听器
            fileInput.onchange = async (event) => {
                const file = event.target.files[0];
                if (!file) {
                    showNotification('请选择要分析的Excel文件', 'error');
                    return;
                }
                
                // 验证文件类型
                if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
                    showNotification('只支持Excel文件(.xlsx, .xls)', 'error');
                    return;
                }
                
                // 执行分析逻辑
                await executeLLMAnalysis(file);
            };
            
            // 将文件输入元素添加到文档中并触发点击
            document.body.appendChild(fileInput);
            fileInput.click();
            document.body.removeChild(fileInput);
        }
        
        // 执行本地大模型分析
        async function executeLLMAnalysis(file) {
            const progressContainer = document.getElementById('llmProgressContainer');
            const progressBar = document.getElementById('llmProgressBar');
            const progressPercent = document.getElementById('llmProgressPercent');
            const progressStatus = document.getElementById('llmProgressStatus');
            const llmAnalyzeBtn = document.getElementById('llmAnalyzeBtn');
            
            try {
                // 显示进度条
                progressContainer.classList.add('show');    //进度条容器从隐藏状态变为显示状态
                llmAnalyzeBtn.disabled = true;  //用 llmAnalyzeBtn 按钮
                llmAnalyzeBtn.style.opacity = '0.6';    //调整按钮的不透明度为 0.6
                llmAnalyzeBtn.style.cursor = 'not-allowed'; //将鼠标悬停在按钮上时通常显示为一个带斜线的圆圈
                
                // 模拟进度更新,steps一个存储所有步骤信息的数组（每个元素是一个包含 percent、status、id 等属性的对象）
                const steps = [
                    { id: 'step1', percent: 10, status: '正在读取Excel文件...' },
                    { id: 'step2', percent: 30, status: '正在分析数据...' },
                    { id: 'step3', percent: 50, status: '正在生成图表...' },
                    { id: 'step4', percent: 70, status: '正在调用本地大模型...' },
                    { id: 'step5', percent: 90, status: '正在生成报告...' }
                ];
                
                let currentStep = 0;
                
                // 更新进度的函数
                function updateProgress() {
                    if (currentStep < steps.length) {
                        const step = steps[currentStep];
                        progressBar.style.width = `${step.percent}%`;
                        progressPercent.textContent = `${step.percent}%`;
                        progressStatus.textContent = step.status;
                        
                        // 更新步骤状态
                        const stepEl = document.getElementById(step.id);
                        stepEl.classList.remove('completed');
                        stepEl.classList.add('active');
                        
                        currentStep++;
                    }
                }
                
                // 定时更新进度
                const progressInterval = setInterval(updateProgress, 1500); // 每1.5秒更新一次进度
                //是一个封装好的通知提示函数（通常用于前端页面展示提示信息）
                showNotification('正在调用本地大模型分析告警数据...', 'info');
                
                // 创建FormData对象上传文件
                const formData = new FormData();
                formData.append('file', file);
                
                // 调用API
                //将请求的响应结果（Response 对象）存储在 response 变量中，后续可通过该变量获取响应状态、响应体等信息
                const response = await fetch(`${API_BASE}/llm/analyze`, {
                    method: 'POST',
                    body: formData
                });
                
                // 清除进度更新定时器
                clearInterval(progressInterval);
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // 完成所有步骤
                    progressBar.style.width = '100%';
                    progressPercent.textContent = '100%';
                    progressStatus.textContent = '✅ 分析完成！';
                    
                    // 标记所有步骤为完成
                    steps.forEach(step => {
                        const stepEl = document.getElementById(step.id);
                        stepEl.classList.remove('active');
                        stepEl.classList.add('completed');
                    });
                    
                    showNotification(result.message || '分析报告生成成功', 'success');
                    
                    // 3秒后隐藏进度条
                    setTimeout(() => {
                        progressContainer.classList.remove('show');
                        resetProgress();    //调用 resetProgress 函数重置进度相关的状态（例如将 currentStep 重置为 0，为下一次操作做准备）
                    }, 3000);
                } else {
                    const error = await response.json();
                    throw new Error(error.detail || '调用大模型分析失败');
                }
            } catch (error) {
                console.error('调用大模型分析失败:', error);
                showNotification('调用大模型分析失败: ' + error.message, 'error');
                
                // 错误时也隐藏进度条
                setTimeout(() => {
                    progressContainer.classList.remove('show');
                    resetProgress();
                }, 2000);
            } finally {
                // 恢复按钮状态
                llmAnalyzeBtn.disabled = false;
                llmAnalyzeBtn.style.opacity = '1';
                llmAnalyzeBtn.style.cursor = 'pointer';
            }
        }
        
        // 重置进度条
        function resetProgress() {
            const progressBar = document.getElementById('llmProgressBar');
            const progressPercent = document.getElementById('llmProgressPercent');
            const progressStatus = document.getElementById('llmProgressStatus');
            
            progressBar.style.width = '0%';
            progressPercent.textContent = '0%';
            progressStatus.textContent = '准备中...';
            
            // 重置所有步骤
            const steps = ['step1', 'step2', 'step3', 'step4', 'step5'];
            steps.forEach(stepId => {
                const stepEl = document.getElementById(stepId);
                stepEl.classList.remove('active', 'completed');
            });
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const detailModal = document.getElementById('detailModal');
            if (event.target === detailModal) {
                closeDetailModal();
            }
        }
        
        // 导入告警
        async function importAlarms() {
            try {
                const fileInput = document.getElementById('alarmFile');
                const file = fileInput.files[0];
                
                if (!file) {
                    showNotification('请选择要导入的文件', 'error');
                    return;
                }
                
                // 验证文件类型
                if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
                    showNotification('只支持Excel文件(.xlsx, .xls)', 'error');
                    return;
                }
                
                showNotification('正在导入告警数据...', 'info');
                
                // 创建FormData对象上传文件
                const formData = new FormData();
                formData.append('file', file);
                
                const response = await fetch(`${API_BASE}/import/excel`, {
                    method: 'POST',
                    body: formData
                });
                
                if (response.ok) {
                    const result = await response.json();
                    // 构建详细的导入结果消息
                    let messageParts = [];
                    messageParts.push(`共 ${result.total_rows} 行`);
                    messageParts.push(`成功 ${result.success_count} 条`);
                    
                    // 添加重复数量信息（如果后端返回了该字段）
                    if (result.duplicate_count !== undefined && result.duplicate_count > 0) {
                        messageParts.push(`重复 ${result.duplicate_count} 条`);
                    }
                    
                    // 添加失败数量信息
                    if (result.fail_count > 0) {
                        messageParts.push(`失败 ${result.fail_count} 条`);
                    }
                    
                    const message = `导入完成！${messageParts.join('，')}`;
                    showNotification(message, 'success');
                    
                    // 清空文件选择
                    fileInput.value = '';
                    // 刷新告警列表
                    await refreshAlarms();
                    // 刷新柱状图
                    await loadCharts();
                } else {
                    const error = await response.json();
                    showNotification(`导入失败: ${error.detail}`, 'error');
                }
            } catch (error) {
                console.error('导入告警失败:', error);
                showNotification('导入告警失败: ' + error.message, 'error');
            }
        }
        
        // 渲染告警表格
        function renderAlarms(alarms) {
            alarmTableBody.innerHTML = '';
            
            if (!alarms || alarms.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="15" style="text-align: center; color: #999;">暂无告警数据</td>';
                alarmTableBody.appendChild(row);
                return;
            }
            
            alarms.forEach(alarm => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${alarm.global_alarm_id || '-'}</td>
                    <td>${alarm.alarm_title || '-'}</td>
                    <td><span class="level-${alarm.alarm_level}">${getLevelText(alarm.alarm_level)}</span></td>
                    <td>${alarm.alarm_type || '-'}</td>
                    <td><span class="status-${alarm.alarm_status}">${getStatusText(alarm.alarm_status)}</span></td>
                    <td>${alarm.occurrence_time ? formatDateTime(alarm.occurrence_time) : '-'}</td>
                    <td>${alarm.clear_time ? formatDateTime(alarm.clear_time) : '未清除'}</td>
                    <td>${alarm.region || '-'}</td>
                    <td>${alarm.datacenter || '-'}</td>
                    <td>${alarm.device_name || '-'}</td>
                    <td>${alarm.device_type || '-'}</td>
                    <td>${alarm.device_vendor || '-'}</td>
                    <td>${alarm.dispatch_status || '-'}</td>
                    <td>${alarm.resource_pool || '-'}</td>
                    <td><button class="btn-detail" onclick="viewAlarmDetail('${alarm.global_alarm_id}'); event.stopPropagation();">查看详情</button></td>
                `;
                alarmTableBody.appendChild(row);
            });
        }
        
        // 获取告警级别文本
        function getLevelText(level) {
            const levelMap = {
                'critical': '严重',
                'major': '重要',
                'minor': '次要',
                'warning': '警告'
            };
            return levelMap[level] || level;
        }
        
        // 获取告警状态文本
        function getStatusText(status) {
            const statusMap = {
                'processing': '处理中',
                'resolved': '已解决',
                'unresolved': '未解决'
            };
            return statusMap[status] || status;
        }
        
        // 查看告警详情
        async function viewAlarmDetail(globalAlarmId) {
            try {
                showNotification('正在加载详情...', 'info');
                const response = await fetch(`${API_BASE}/${globalAlarmId}`);
                if (response.ok) {
                    const alarm = await response.json();
                    displayAlarmDetail(alarm);
                    showNotification('详情加载成功', 'success');
                } else {
                    showNotification('获取告警详情失败', 'error');
                }
            } catch (error) {
                console.error('获取告警详情失败:', error);
                showNotification('获取告警详情失败: ' + error.message, 'error');
            }
        }
        
        // 显示告警详情
        function displayAlarmDetail(alarm) {
            const detailContent = document.getElementById('detailContent');
            
            detailContent.innerHTML = `
                <div class="detail-item">
                    <div class="detail-label">告警全局标识：</div>
                    <div class="detail-value">${alarm.global_alarm_id || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警标题：</div>
                    <div class="detail-value">${alarm.alarm_title || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">标准告警级别：</div>
                    <div class="detail-value"><span class="level-${alarm.alarm_level}">${getLevelText(alarm.alarm_level)}</span></div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警类型：</div>
                    <div class="detail-value">${alarm.alarm_type || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警状态：</div>
                    <div class="detail-value"><span class="status-${alarm.alarm_status}">${getStatusText(alarm.alarm_status)}</span></div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警发生时间：</div>
                    <div class="detail-value">${alarm.occurrence_time ? formatDateTime(alarm.occurrence_time) : '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警清除时间：</div>
                    <div class="detail-value">${alarm.clear_time ? formatDateTime(alarm.clear_time) : '未清除'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">大区：</div>
                    <div class="detail-value">${alarm.region || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">机房：</div>
                    <div class="detail-value">${alarm.datacenter || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">设备名称：</div>
                    <div class="detail-value">${alarm.device_name || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">设备类型：</div>
                    <div class="detail-value">${alarm.device_type || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">设备厂商：</div>
                    <div class="detail-value">${alarm.device_vendor || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">派单状态：</div>
                    <div class="detail-value">${alarm.dispatch_status || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">资源池：</div>
                    <div class="detail-value">${alarm.resource_pool || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警次数：</div>
                    <div class="detail-value">${alarm.alarm_count || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">告警正文：</div>
                    <div class="detail-value" style="white-space: pre-wrap;">${alarm.alarm_content || '无'}</div>
                </div>
            `;
            
            // 显示模态框
            document.getElementById('detailModal').classList.add('show');
        }
        
        // 关闭详情模态框
        function closeDetailModal() {
            document.getElementById('detailModal').classList.remove('show');
        }
        
        // 格式化日期时间
        function formatDateTime(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
        }
        
        // 更新分页信息
        async function updatePagination() {
            try {
                // 获取总告警数
                const response = await fetch(`${API_BASE}/query/count`);
                if (response.ok) {
                    totalAlarms = await response.json();
                    const totalPages = Math.ceil(totalAlarms / pageSize);
                    
                    currentPageEl.textContent = currentPage;
                    totalPagesEl.textContent = totalPages;
                    
                    // 更新分页按钮状态
                    document.getElementById('prevPage').disabled = currentPage <= 1;
                    document.getElementById('nextPage').disabled = currentPage >= totalPages;
                }
            } catch (error) {
                console.error('更新分页信息失败:', error);
            }
        }
        
        // 上一页
        function prevPage() {
            if (currentPage > 1) {
                currentPage--;
                refreshAlarms();
            }
        }
        
        // 下一页
        function nextPage() {
            currentPage++;
            refreshAlarms();
        }
        
        // 显示通知
        function showNotification(message, type, duration = 3000) {
            notificationEl.textContent = message;
            notificationEl.className = `notification ${type} show`;
            
            setTimeout(() => {
                notificationEl.classList.remove('show');
            }, duration);
        }

        // ==================== 柱状图功能 ====================
        
        // 存储图表实例
        let chart1Instance = null;
        let chart2Instance = null;
        let chart3Instance = null;
        let chart4Instance = null;
        
        // 加载柱状图数据
        async function loadCharts() {
            try {
                showNotification('正在加载图表数据...', 'info');
                const response = await fetch(`${API_BASE}/analysis/charts`);
                
                if (response.ok) {
                    const data = await response.json();
                    if (data.success) {
                        // 渲染图表
                        renderChart1(data.charts.alarm_title_trend);
                        renderChart2(data.charts.device_alarm_trend);
                        renderChart3(data.charts.vendor_trend);
                        renderChart4(data.charts.level_trend);
                        showNotification('图表数据加载成功', 'success');
                    } else {
                        showNotification(data.message || '图表数据加载失败', 'error');
                    }
                } else {
                    throw new Error('获取图表数据失败');
                }
            } catch (error) {
                console.error('加载图表数据失败:', error);
                showNotification('加载图表数据失败: ' + error.message, 'error');
            }
        }
        
        // 场景1：告警标题趋势图
        function renderChart1(data) {
            const ctx = document.getElementById('chart1').getContext('2d');
            
            // 销毁旧图表
            if (chart1Instance) {
                chart1Instance.destroy();
            }
            
            chart1Instance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: '告警数量',
                        data: data.values,
                        backgroundColor: 'rgba(102, 126, 234, 0.7)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            enabled: true
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        },
                        x: {
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        }
                    }
                }
            });
        }
        
        // 场景2：设备告警趋势图
        function renderChart2(data) {
            const ctx = document.getElementById('chart2').getContext('2d');
            
            // 销毁旧图表
            if (chart2Instance) {
                chart2Instance.destroy();
            }
            
            chart2Instance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: '告警数量',
                        data: data.values,
                        backgroundColor: 'rgba(40, 167, 69, 0.7)',
                        borderColor: 'rgba(40, 167, 69, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            enabled: true
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        },
                        x: {
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        }
                    }
                }
            });
        }
        
        // 场景3：设备厂商趋势图
        function renderChart3(data) {
            const ctx = document.getElementById('chart3').getContext('2d');
            
            // 销毁旧图表
            if (chart3Instance) {
                chart3Instance.destroy();
            }
            
            chart3Instance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: '告警数量',
                        data: data.values,
                        backgroundColor: 'rgba(255, 193, 7, 0.7)',
                        borderColor: 'rgba(255, 193, 7, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            enabled: true
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        },
                        x: {
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        }
                    }
                }
            });
        }
        
        // 场景4：告警级别趋势图
        function renderChart4(data) {
            const ctx = document.getElementById('chart4').getContext('2d');
            
            // 销毁旧图表
            if (chart4Instance) {
                chart4Instance.destroy();
            }
            
            // 级别颜色映射
            const levelColors = {
                '严重': 'rgba(220, 53, 69, 0.7)',
                '重要': 'rgba(253, 126, 20, 0.7)',
                '次要': 'rgba(255, 193, 7, 0.7)',
                '警告': 'rgba(40, 167, 69, 0.7)'
            };
            
            const backgroundColors = data.labels.map(label => levelColors[label] || 'rgba(108, 117, 125, 0.7)');
            
            chart4Instance = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: '告警数量',
                        data: data.values,
                        backgroundColor: backgroundColors,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            enabled: true
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        }
                    }
                }
            });
        }
    </script>
</body>
</html>